package com.woniu.postbar.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.common.constant.PostBarConstant;
import com.woniu.common.constant.RedisKeyConstant;
import com.woniu.common.entity.PageData;
import com.woniu.common.entity.ResultCode;
import com.woniu.common.exception.LifeException;
import com.woniu.postbar.entity.dto.PostCommentDTO;
import com.woniu.postbar.entity.vo.PostBarVO;
import com.woniu.postbar.entity.vo.PostCommentVO;
import com.woniu.postbar.mapper.PostCommentMapper;
import com.woniu.postbar.mapper.UserPostMapper;
import com.woniu.postbar.pojo.PostComment;
import com.woniu.postbar.pojo.UserPost;
import com.woniu.postbar.service.IPostCommentService;
import com.woniu.user.feignClient.UserFeignClient;
import com.woniu.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wu
 * @since 2023-05-20
 */
@Service
public class PostCommentServiceImpl extends ServiceImpl<PostCommentMapper, PostComment> implements IPostCommentService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private PostCommentMapper postCommentMapper;


    @Override
    public boolean addPostComment(PostCommentDTO postCommentDTO) {
        //获取用户的信息
         User user = userFeignClient.getUser(postCommentDTO.getUserId()).getData();
        // 判断用户状态是否可以评论
        if (user.getCommentStatus() == PostBarConstant.COMMENT_STATUS_ERROR) {
            throw new LifeException(ResultCode.USER_COMMENT_STATUS.getMessage());
        }
        //判断是否开启了评论
        if (postCommentDTO.getCommentOpen() == PostBarConstant.COMMENT_STATUS_OPEN) {
            Integer postId = postCommentDTO.getUserPostId();
            String commentId = String.valueOf(postCommentDTO.getUserId());
            if (postCommentDTO.getCommentParentId() == PostBarConstant.REPLY_MESSAGE) {
                // 存储评论内容和点赞数
                String commentKey = RedisKeyConstant.POST_COMMENT + postId + PostBarConstant.COLON + commentId;
                redisTemplate.opsForHash().put(commentKey, PostBarConstant.MESSAGE, postCommentDTO.getMessage());
                redisTemplate.opsForHash().put(commentKey, PostBarConstant.LIKE_COUNT, String.valueOf(postCommentDTO.getCommentLikeCount()));
                redisTemplate.opsForHash().put(commentKey, PostBarConstant.USER_AVATAR, user.getAvatar());
                redisTemplate.opsForHash().put(commentKey, PostBarConstant.USER_NAME, user.getName());
                Double score = (double) System.currentTimeMillis();
                redisTemplate.opsForZSet().add(commentKey, commentId, score);
            }
            if (postCommentDTO.getCommentParentId() != PostBarConstant.REPLY_MESSAGE) {
                String replyKey = RedisKeyConstant.POST_REPLY + postId + PostBarConstant.COLON + commentId;
                redisTemplate.opsForHash().put(replyKey, PostBarConstant.MESSAGE, postCommentDTO.getMessage());
                redisTemplate.opsForHash().put(replyKey, PostBarConstant.LIKE_COUNT, String.valueOf(postCommentDTO.getCommentLikeCount()));
                redisTemplate.opsForHash().put(replyKey, PostBarConstant.USER_AVATAR, user.getAvatar());
                redisTemplate.opsForHash().put(replyKey, PostBarConstant.USER_NAME, user.getName());
                Double score = (double) System.currentTimeMillis();
                redisTemplate.opsForZSet().add(replyKey, commentId, score);
            }
            return true;
        } else {
            throw new LifeException(ResultCode.USER_COMMENT_STATUS_OPEN.getMessage());
        }
    }

    @Override
    public PageData<List<PostCommentVO>> search(Integer currentPage, Integer pageSize, PostCommentDTO postCommentDTO) {
        // 计算分页起始索引
        long start = (currentPage - PostBarConstant.PAGE_NUM) * pageSize;
        // 计算分页结束索引
        long end = start + pageSize - PostBarConstant.PAGE_NUM;
        // 构造评论的有序集合键
        Integer postId = postCommentDTO.getUserPostId();
        String commentId = String.valueOf(postCommentDTO.getUserId());
        String commentKey = RedisKeyConstant.POST_COMMENT + postId + PostBarConstant.COLON + commentId;
        // 获取评论详情，并封装到结果列表中
        List<PostCommentVO> commentList = new ArrayList<>();
        // 从有序集合中按照分数逆序获取指定范围的评论
        Set<Object> commentSet = redisTemplate.opsForZSet().reverseRange(commentKey, start, end);
        if(commentSet !=null && !commentSet.isEmpty()){
            List<Object> commentDetails = redisTemplate.opsForHash().multiGet(commentKey, commentSet);
            for (Object commentDetail : commentDetails) {
                if (commentDetail != null) {
                    PostCommentVO comment = (PostCommentVO) commentDetail;
                    commentList.add(comment);
                }
            }
        }
        // 获取评论总数，并设置到分页数据对象中
        Long total = redisTemplate.opsForZSet().zCard(commentKey);
        // 构造分页数据对象
        PageData<List<PostCommentVO>> pageData = new PageData<>();
        pageData.setCurrentPage(currentPage);
        pageData.setPageSize(pageSize);
        pageData.setTotal(total);
        // 设置评论列表到分页数据对象中
        pageData.setData(commentList);
        return pageData;
    }

//    @Override
//    public List<PostCommentVO> listComment(PostCommentDTO postCommentDTO) {
//        Integer postId = postCommentDTO.getUserPostId();
//        String commentId = String.valueOf(postCommentDTO.getUserId());
//        String commentKey = RedisKeyConstant.POST_COMMENT + postId + PostBarConstant.COLON + commentId;
//        // 查询缓存中是否存在
//        //List<PostCommentVO> postCommentVOList = (List<PostCommentVO>) redisTemplate.opsForHash().get(commentKey,commentId);
//        List<PostCommentVO> postCommentVOList = null;
//        if(redisTemplate.hasKey(commentKey)){
//            postCommentVOList = (List<PostCommentVO>) redisTemplate.opsForHash().get(commentKey, commentId);
//        }
//        // 如果存在直接返回
//        if(postCommentVOList != null && postCommentVOList.size() > PostBarConstant.SIZE){
//            return postCommentVOList;
//        }
//        // 不存在则查询数据库
//        postCommentVOList = postCommentMapper.listAllPostComment();
//        // 将查询出来的结果添加到Redis中
//        redisTemplate.opsForHash().put(commentKey, commentId, postCommentVOList);
//        return postCommentVOList;
//    }
}
